﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Terret : MonoBehaviour {

    public List<GameObject> Enemies = new List<GameObject>();

    void OnTriggerEnter(Collider co)
    {
        if (co.tag == "Enemy")
        {
            Enemies.Add(co.gameObject);
        }
    }

    void OnTriggerExit(Collider co)
    {
        if (co.tag == "Enemy")
        {
            Enemies.Remove(co.gameObject);
        }
    }

    public float attackRateTime = 1;
    private float timer = 0;

    public GameObject bulletPrefab;
    public Transform firePosition;

    void Start()
    {
        timer = attackRateTime;
    }

    void Update()
    {
        timer += Time.deltaTime;
        if (Enemies.Count > 0 && timer > attackRateTime)
        {
            timer -= attackRateTime;
            Attack();
        }
    }

    void Attack()
    {
        GameObject go = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
        go.GetComponent<Bullet>().SetTarget(Enemies[0].transform);
    }
}
